<template>
	<div class="app-container">
		<!-- 顶部导航栏 -->
		<header class="header">
			<div class="logo">
				<el-icon size="24"><Medal /></el-icon>
				运动会管理系统
			</div>
			<div class="flex-grow"></div>
			<div class="user-info">
				<el-dropdown trigger="click">
					<div class="user-avatar">
						<el-avatar :size="40" :src="avatarUrl" icon="UserFilled"></el-avatar>
						<span class="username">{{ currentUser?.realName || '管理员' }}</span>
						<el-icon><ArrowDown /></el-icon>
					</div>
					<template #dropdown>
						<el-dropdown-menu>
							<el-dropdown-item @click="handleLogout">
								<el-icon><SwitchButton /></el-icon>
								退出登录
							</el-dropdown-item>
						</el-dropdown-menu>
					</template>
				</el-dropdown>
			</div>
		</header>

		<!-- 左侧导航栏 -->
		<nav class="sidebar">
			<div class="menu-item" :class="{ active: $route.path === '/admin' }" @click="navigateTo('/admin')">
				<el-icon><Monitor /></el-icon>
				<span>系统管理</span>
			</div>
			<div class="menu-item" :class="{ active: $route.path === '/admin/users' }" @click="navigateTo('/admin/users')">
				<el-icon><User /></el-icon>
				<span>用户管理</span>
			</div>
			<div class="menu-item active">
				<el-icon><List /></el-icon>
				<span>项目管理</span>
			</div>
			<div class="menu-item" :class="{ active: $route.path === '/admin/schedule' }" @click="navigateTo('/admin/schedule')">
				<el-icon><Calendar /></el-icon>
				<span>赛程管理</span>
			</div>
			<div class="menu-item" :class="{ active: $route.path === '/admin/judges' }" @click="navigateTo('/admin/judges')">
				<el-icon><Whistle /></el-icon>
				<span>裁判分配</span>
			</div>
		</nav>

		<!-- 主要内容 -->
		<main class="content">
			<!-- 页面标题和操作按钮 -->
			<div class="page-header">
				<div class="page-title">
					<h1>项目管理</h1>
					<p class="page-desc">管理运动会项目信息、项目分类和状态控制</p>
				</div>
				<div class="header-actions">
					<el-button type="success" @click="handleExport" :loading="exportLoading">
						<el-icon><Download /></el-icon> 导出数据
					</el-button>
					<el-button type="primary" @click="handleAdd">
						<el-icon><Plus /></el-icon> 添加项目
					</el-button>
				</div>
			</div>

			<!-- 搜索和筛选区域 -->
			<el-card class="search-card" shadow="hover">
				<el-form :model="searchForm" inline>
					<el-row :gutter="20">
						<el-col :xs="24" :sm="12" :md="8" :lg="6">
							<el-form-item label="项目名称">
								<el-input
									v-model="searchForm.name"
									placeholder="请输入项目名称"
									clearable
									:prefix-icon="Search"
									@keyup.enter="handleSearch">
								</el-input>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12" :md="8" :lg="6">
							<el-form-item label="项目类型">
								<el-select
									v-model="searchForm.type"
									placeholder="请选择项目类型"
									clearable
									style="width: 100%">
									<el-option
										v-for="type in projectTypes"
										:key="type"
										:label="type"
										:value="type">
									</el-option>
								</el-select>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12" :md="8" :lg="6">
							<el-form-item label="项目状态">
								<el-select
									v-model="searchForm.status"
									placeholder="请选择项目状态"
									clearable
									style="width: 100%">
									<el-option
										v-for="status in projectStatuses"
										:key="status"
										:label="status"
										:value="status">
									</el-option>
								</el-select>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12" :md="8" :lg="6">
							<el-form-item label="性别限制">
								<el-select
									v-model="searchForm.genderLimit"
									placeholder="请选择性别限制"
									clearable
									style="width: 100%">
									<el-option
										v-for="limit in genderLimits"
										:key="limit"
										:label="limit"
										:value="limit">
									</el-option>
								</el-select>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12" :md="8" :lg="6">
							<el-form-item>
								<el-button type="primary" @click="handleSearch" :loading="loading">
									<el-icon><Search /></el-icon> 搜索
								</el-button>
								<el-button @click="handleReset">
									<el-icon><Refresh /></el-icon> 重置
								</el-button>
								<el-button type="info" @click="toggleAdvancedSearch">
									<el-icon><Operation /></el-icon> {{ showAdvancedSearch ? '收起' : '高级' }}
								</el-button>
							</el-form-item>
						</el-col>
					</el-row>

					<!-- 高级搜索区域 -->
					<el-collapse-transition>
						<div v-show="showAdvancedSearch" class="advanced-search">
							<el-divider content-position="left">高级搜索</el-divider>
							<el-row :gutter="20">
								<el-col :xs="24" :sm="12" :md="8" :lg="6">
									<el-form-item label="创建人">
										<el-input
											v-model="searchForm.creator"
											placeholder="请输入创建人"
											clearable
											:prefix-icon="UserFilled"
											@keyup.enter="handleSearch">
										</el-input>
									</el-form-item>
								</el-col>
								<el-col :xs="24" :sm="12" :md="8" :lg="6">
									<el-form-item label="最大人数">
										<el-input-number
											v-model="searchForm.maxPlayers"
											placeholder="最大参赛人数"
											:controls="false"
											style="width: 100%">
										</el-input-number>
									</el-form-item>
								</el-col>
								<el-col :xs="24" :sm="12" :md="8" :lg="6">
									<el-form-item label="创建时间">
										<el-date-picker
											v-model="searchForm.dateRange"
											type="daterange"
											range-separator="至"
											start-placeholder="开始日期"
											end-placeholder="结束日期"
											style="width: 100%"
											format="YYYY-MM-DD"
											value-format="YYYY-MM-DD">
										</el-date-picker>
									</el-form-item>
								</el-col>
							</el-row>
						</div>
					</el-collapse-transition>
				</el-form>
			</el-card>

			<!-- 项目数据表格 -->
			<el-card class="table-card" shadow="hover">
				<!-- 工具栏 -->
				<div class="table-toolbar">
					<div class="table-info">
						<span class="table-title">项目列表</span>
						<el-tag type="info" size="small">共 {{ pagination.total }} 条记录</el-tag>
					</div>
					<div class="table-actions">
						<el-button-group>
							<el-button
								:size="tableSize"
								@click="tableSize = 'large'"
								:class="{ 'is-active': tableSize === 'large' }">
								大
							</el-button>
							<el-button
								:size="tableSize"
								@click="tableSize = 'default'"
								:class="{ 'is-active': tableSize === 'default' }">
								中
							</el-button>
							<el-button
								:size="tableSize"
								@click="tableSize = 'small'"
								:class="{ 'is-active': tableSize === 'small' }">
								小
							</el-button>
						</el-button-group>
						<el-button
							:icon="RefreshRight"
							@click="loadData"
							:loading="loading"
							circle>
						</el-button>
					</div>
				</div>

				<!-- 表格主体 -->
				<el-table
					:data="tableData"
					v-loading="loading"
					:height="tableHeight"
					stripe
					border
					:size="tableSize"
					@selection-change="handleSelectionChange"
					@sort-change="handleSortChange"
					style="width: 100%">
					<el-table-column type="selection" width="55" align="center" fixed="left"></el-table-column>
					<el-table-column prop="id" label="ID" width="80" align="center" sortable="custom"></el-table-column>
					<el-table-column prop="name" label="项目名称" width="180" align="center" show-overflow-tooltip>
						<template #default="scope">
							<el-link type="primary" @click="handleViewDetail(scope.row)">{{ scope.row.name }}</el-link>
						</template>
					</el-table-column>
					<el-table-column prop="type" label="项目类型" width="100" align="center">
						<template #default="scope">
							<el-tag :type="getTypeTagType(scope.row.type)" size="small">
								{{ scope.row.type }}
							</el-tag>
						</template>
					</el-table-column>
					<el-table-column prop="genderLimit" label="性别限制" width="100" align="center">
						<template #default="scope">
							<el-tag :type="getGenderTagType(scope.row.genderLimit)" size="small">
								{{ scope.row.genderLimit }}
							</el-tag>
						</template>
					</el-table-column>
					<el-table-column prop="maxPlayers" label="最大人数" width="100" align="center" sortable="custom"></el-table-column>
					<el-table-column prop="registrationCount" label="已报名" width="100" align="center">
						<template #default="scope">
							<div class="registration-info">
								<span>{{ scope.row.registrationCount || 0 }}</span>
								<span class="registration-percent">({{ getRegistrationPercent(scope.row) }}%)</span>
							</div>
						</template>
					</el-table-column>
					<el-table-column prop="rounds" label="轮次" width="80" align="center"></el-table-column>
					<el-table-column prop="status" label="状态" width="100" align="center">
						<template #default="scope">
							<el-switch
								v-model="scope.row.isActive"
								:loading="scope.row.statusLoading"
								@change="handleToggleStatus(scope.row)"
								active-color="#67C23A"
								inactive-color="#F56C6C">
							</el-switch>
							<el-tag :type="getStatusTagType(scope.row.status)" size="small" style="margin-left: 8px">
								{{ scope.row.status }}
							</el-tag>
						</template>
					</el-table-column>
					<el-table-column prop="creator.realName" label="创建人" width="120" align="center" show-overflow-tooltip>
						<template #default="scope">
							<span>{{ scope.row.creator?.realName || '-' }}</span>
						</template>
					</el-table-column>
					<el-table-column prop="createdAt" label="创建时间" width="160" align="center" sortable="custom">
						<template #default="scope">
							{{ formatDateTime(scope.row.createdAt) }}
						</template>
					</el-table-column>
					<el-table-column label="操作" width="250" align="center" fixed="right">
						<template #default="scope">
							<el-button-group>
								<el-tooltip content="查看详情" placement="top">
									<el-button
										type="primary"
										:icon="View"
										size="small"
										@click="handleViewDetail(scope.row)">
									</el-button>
								</el-tooltip>
								<el-tooltip content="编辑" placement="top">
									<el-button
										type="primary"
										:icon="Edit"
										size="small"
										@click="handleEdit(scope.row)">
									</el-button>
								</el-tooltip>
								<el-tooltip content="修改状态" placement="top">
									<el-button
										:type="getStatusButtonType(scope.row.status)"
										:icon="RefreshRight"
										size="small"
										@click="handleUpdateStatus(scope.row)">
									</el-button>
								</el-tooltip>
								<el-tooltip content="删除" placement="top">
									<el-button
										type="danger"
										:icon="Delete"
										size="small"
										@click="handleDelete(scope.row)">
									</el-button>
								</el-tooltip>
							</el-button-group>
						</template>
					</el-table-column>
				</el-table>

				<!-- 分页控制 -->
				<div class="pagination-container">
					<el-pagination
						v-model:current-page="pagination.currentPage"
						v-model:page-size="pagination.pageSize"
						:page-sizes="[10, 20, 50, 100]"
						:total="pagination.total"
						layout="total, sizes, prev, pager, next, jumper"
						@size-change="handleSizeChange"
						@current-change="handleCurrentChange"
						background>
					</el-pagination>
				</div>

				<!-- 批量操作栏 -->
				<div class="batch-operations" v-if="selectedProjects.length > 0">
					<div class="batch-info">
						<el-icon><Select /></el-icon>
						<span>已选择 {{ selectedProjects.length }} 项</span>
					</div>
					<div class="batch-actions">
						<el-button-group>
							<el-button type="danger" @click="handleBatchDelete" :loading="batchLoading">
								<el-icon><Delete /></el-icon> 批量删除
							</el-button>
							<el-button type="warning" @click="handleBatchUpdateStatus('已取消')" :loading="batchLoading">
								<el-icon><Close /></el-icon> 批量取消
							</el-button>
							<el-button type="success" @click="handleBatchUpdateStatus('报名中')" :loading="batchLoading">
								<el-icon><Check /></el-icon> 批量开启报名
							</el-button>
						</el-button-group>
					</div>
				</div>
			</el-card>

			<!-- 项目表单对话框 -->
			<el-dialog
				:title="dialogTitle"
				v-model="dialogVisible"
				width="700px"
				:before-close="handleDialogClose"
				:close-on-click-modal="false"
				destroy-on-close>
				<el-form
					:model="projectForm"
					:rules="projectFormRules"
					ref="projectFormRef"
					label-width="100px"
					:size="formSize">
					<el-row :gutter="20">
						<el-col :xs="24" :sm="12">
							<el-form-item label="项目名称" prop="name">
								<el-input
									v-model="projectForm.name"
									placeholder="请输入项目名称"
									:prefix-icon="Edit">
								</el-input>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12">
							<el-form-item label="项目类型" prop="type">
								<el-select
									v-model="projectForm.type"
									placeholder="请选择项目类型"
									style="width: 100%">
									<el-option
										v-for="type in projectTypes"
										:key="type"
										:label="type"
										:value="type">
									</el-option>
								</el-select>
							</el-form-item>
						</el-col>
					</el-row>
					<el-row :gutter="20">
						<el-col :xs="24" :sm="12">
							<el-form-item label="性别限制" prop="genderLimit">
								<el-select
									v-model="projectForm.genderLimit"
									placeholder="请选择性别限制"
									style="width: 100%">
									<el-option
										v-for="limit in genderLimits"
										:key="limit"
										:label="limit"
										:value="limit">
									</el-option>
								</el-select>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12">
							<el-form-item label="项目状态" prop="status">
								<el-select
									v-model="projectForm.status"
									placeholder="请选择项目状态"
									style="width: 100%">
									<el-option
										v-for="status in projectStatuses"
										:key="status"
										:label="status"
										:value="status">
									</el-option>
								</el-select>
							</el-form-item>
						</el-col>
					</el-row>
					<el-row :gutter="20">
						<el-col :xs="24" :sm="12">
							<el-form-item label="最大参赛人数" prop="maxPlayers">
								<el-input-number
									v-model="projectForm.maxPlayers"
									:min="1"
									:max="1000"
									placeholder="请输入最大参赛人数"
									style="width: 100%">
								</el-input-number>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12">
							<el-form-item label="轮次数量" prop="rounds">
								<el-input-number
									v-model="projectForm.rounds"
									:min="1"
									:max="10"
									placeholder="请输入轮次数量"
									style="width: 100%">
								</el-input-number>
							</el-form-item>
						</el-col>
					</el-row>
					<el-row :gutter="20">
						<el-col :span="24">
							<el-form-item label="规则描述" prop="ruleDescription">
								<el-input
									v-model="projectForm.ruleDescription"
									type="textarea"
									:rows="4"
									placeholder="请输入规则描述">
								</el-input>
							</el-form-item>
						</el-col>
					</el-row>
				</el-form>
				<template #footer>
					<div class="dialog-footer">
						<el-button @click="handleDialogClose">取消</el-button>
						<el-button type="primary" @click="handleSave" :loading="saveLoading">
							确定
						</el-button>
					</div>
				</template>
			</el-dialog>

			<!-- 项目详情对话框 -->
			<el-dialog
				title="项目详情"
				v-model="detailDialogVisible"
				width="600px">
				<div v-if="currentProjectDetail" class="project-detail">
					<el-descriptions :column="2" border>
						<el-descriptions-item label="项目名称">{{ currentProjectDetail.name }}</el-descriptions-item>
						<el-descriptions-item label="项目类型">
							<el-tag :type="getTypeTagType(currentProjectDetail.type)">
								{{ currentProjectDetail.type }}
							</el-tag>
						</el-descriptions-item>
						<el-descriptions-item label="性别限制">
							<el-tag :type="getGenderTagType(currentProjectDetail.genderLimit)">
								{{ currentProjectDetail.genderLimit }}
							</el-tag>
						</el-descriptions-item>
						<el-descriptions-item label="项目状态">
							<el-tag :type="getStatusTagType(currentProjectDetail.status)">
								{{ currentProjectDetail.status }}
							</el-tag>
						</el-descriptions-item>
						<el-descriptions-item label="最大参赛人数">{{ currentProjectDetail.maxPlayers }}</el-descriptions-item>
						<el-descriptions-item label="已报名人数">{{ currentProjectDetail.registrationCount || 0 }}</el-descriptions-item>
						<el-descriptions-item label="轮次数量">{{ currentProjectDetail.rounds }}</el-descriptions-item>
						<el-descriptions-item label="创建人">{{ currentProjectDetail.creator?.realName || '-' }}</el-descriptions-item>
						<el-descriptions-item label="创建时间">{{ formatDateTime(currentProjectDetail.createdAt) }}</el-descriptions-item>
						<el-descriptions-item label="规则描述" :span="2">
							<div class="rule-description">{{ currentProjectDetail.ruleDescription || '-' }}</div>
						</el-descriptions-item>
					</el-descriptions>
				</div>
			</el-dialog>
		</main>
	</div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  // 图标组件
  Medal, User, Monitor, List, Calendar, Whistle, ArrowDown, SwitchButton,
  Download, Plus, Search, Refresh, Operation, UserFilled, View,
  Edit, Delete, RefreshRight, Check, Close, Select
} from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'
import { useStore } from 'vuex'

// 导入API接口
import {
  getProjectPage, getProjectById, addProject, updateProject, deleteProject,
  batchDeleteProjects, updateProjectStatus, batchUpdateProjectStatus,
  getProjectTypes, getProjectStatuses, getGenderLimits
} from '@/api/project'

// 路由和状态管理
const router = useRouter()
const store = useStore()

// 响应式数据
const loading = ref(false)
const saveLoading = ref(false)
const exportLoading = ref(false)
const batchLoading = ref(false)
const dialogVisible = ref(false)
const detailDialogVisible = ref(false)
const showAdvancedSearch = ref(false)
const isEdit = ref(false)
const tableSize = ref('default')
const formSize = ref('default')

// 表格高度
const tableHeight = ref(600)

// 搜索表单
const searchForm = reactive({
  name: '',
  type: '',
  status: '',
  genderLimit: '',
  creator: '',
  maxPlayers: null,
  dateRange: null,
  sortBy: '',
  sortOrder: ''
})

// 分页信息
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 表格数据
const tableData = ref([])
const selectedProjects = ref([])

// 项目详情
const currentProjectDetail = ref(null)

// 当前用户信息
const currentUser = computed(() => store.state.user || JSON.parse(localStorage.getItem('user')))

// 默认头像URL
const avatarUrl = computed(() => '/img/jstu1.webp')

// 项目选项
const projectTypes = ref([])
const projectStatuses = ref([])
const genderLimits = ref(['无', '男', '女'])

// 项目表单
const projectForm = reactive({
  id: null,
  name: '',
  type: '',
  genderLimit: '无',
  maxPlayers: 50,
  rounds: 1,
  ruleDescription: '',
  status: '未开始'
})

// 上传文件变量已预留，用于后续文件上传功能扩展

// 对话框标题
const dialogTitle = computed(() => isEdit.value ? '编辑项目' : '添加项目')

// 表单引用
const projectFormRef = ref(null)

// 表单验证规则
const projectFormRules = reactive({
  name: [
    { required: true, message: '请输入项目名称', trigger: 'blur' },
    { min: 2, max: 50, message: '项目名称长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择项目类型', trigger: 'change' }
  ],
  genderLimit: [
    { required: true, message: '请选择性别限制', trigger: 'change' }
  ],
  maxPlayers: [
    { required: true, message: '请输入最大参赛人数', trigger: 'blur' },
    { type: 'number', min: 1, message: '最大参赛人数至少为1', trigger: 'blur' }
  ],
  rounds: [
    { required: true, message: '请输入轮次数量', trigger: 'blur' },
    { type: 'number', min: 1, message: '轮次数量至少为1', trigger: 'blur' }
  ],
  status: [
    { required: true, message: '请选择项目状态', trigger: 'change' }
  ]
})


// 切换高级搜索
const toggleAdvancedSearch = () => {
  showAdvancedSearch.value = !showAdvancedSearch.value
}

// 初始化数据
const initData = async () => {
  await loadProjectTypes()
  await loadProjectStatuses()
  await loadGenderLimits()
  loadData()
}

// 加载数据
const loadData = async () => {
  loading.value = true
  try {
    // 处理日期范围
    const params = { ...searchForm }
    if (params.dateRange && params.dateRange.length === 2) {
      params.startDate = params.dateRange[0]
      params.endDate = params.dateRange[1]
    }
    delete params.dateRange

    const response = await getProjectPage(pagination.currentPage, pagination.pageSize, params)

    if (response.code === 200) {
      tableData.value = response.data.records.map(item => ({
        ...item,
        statusLoading: false,
        isActive: item.status !== '已取消' // 简化处理，非取消状态为激活
      }))
      pagination.total = response.data.total
    } else {
      ElMessage.error(response.message || '获取数据失败')
    }
  } catch (error) {
    console.error('获取项目数据失败:', error)
    ElMessage.error('获取数据失败')
  } finally {
    loading.value = false
  }
}

// 加载项目类型
const loadProjectTypes = async () => {
  try {
    const response = await getProjectTypes()
    if (response.code === 200) {
      projectTypes.value = response.data
    }
  } catch (error) {
    console.error('获取项目类型失败:', error)
  }
}

// 加载项目状态
const loadProjectStatuses = async () => {
  try {
    const response = await getProjectStatuses()
    if (response.code === 200) {
      projectStatuses.value = response.data
    }
  } catch (error) {
    console.error('获取项目状态失败:', error)
  }
}

// 加载性别限制
const loadGenderLimits = async () => {
  try {
    const response = await getGenderLimits()
    if (response.code === 200) {
      genderLimits.value = response.data
    }
  } catch (error) {
    console.error('获取性别限制失败:', error)
  }
}

// 搜索
const handleSearch = () => {
  pagination.currentPage = 1
  loadData()
}

// 重置搜索
const handleReset = () => {
  Object.assign(searchForm, {
    name: '',
    type: '',
    status: '',
    genderLimit: '',
    creator: '',
    maxPlayers: null,
    dateRange: null,
    sortBy: '',
    sortOrder: ''
  })
  handleSearch()
}

// 分页大小改变
const handleSizeChange = (val) => {
  pagination.pageSize = val
  loadData()
}

// 当前页改变
const handleCurrentChange = (val) => {
  pagination.currentPage = val
  loadData()
}

// 表格排序改变
const handleSortChange = ({ prop, order }) => {
  searchForm.sortBy = prop
  searchForm.sortOrder = order === 'ascending' ? 'asc' : order === 'descending' ? 'desc' : ''
  loadData()
}

// 表格选择改变
const handleSelectionChange = (selection) => {
  selectedProjects.value = selection
}

// 添加项目
const handleAdd = () => {
  isEdit.value = false
  resetProjectForm()
  dialogVisible.value = true
}

// 编辑项目
const handleEdit = async (row) => {
  isEdit.value = true
  try {
    const response = await getProjectById(row.id)
    if (response.code === 200) {
      Object.assign(projectForm, response.data)
      dialogVisible.value = true
    } else {
      ElMessage.error(response.message || '获取项目信息失败')
    }
  } catch (error) {
    console.error('获取项目信息失败:', error)
    ElMessage.error('获取项目信息失败')
  }
}

// 查看项目详情
const handleViewDetail = async (row) => {
  try {
    const response = await getProjectById(row.id)
    if (response.code === 200) {
      currentProjectDetail.value = response.data
      detailDialogVisible.value = true
    } else {
      ElMessage.error(response.message || '获取项目详情失败')
    }
  } catch (error) {
    console.error('获取项目详情失败:', error)
    ElMessage.error('获取项目详情失败')
  }
}

// 保存项目
const handleSave = async () => {
  if (!projectFormRef.value) return

  await projectFormRef.value.validate(async (valid) => {
    if (valid) {
      saveLoading.value = true
      try {
        let response
        if (isEdit.value) {
          response = await updateProject(projectForm)
        } else {
          response = await addProject(projectForm)
        }

        if (response.code === 200) {
          ElMessage.success(isEdit.value ? '更新成功' : '添加成功')
          dialogVisible.value = false
          loadData()
        } else {
          ElMessage.error(response.message || (isEdit.value ? '更新失败' : '添加失败'))
        }
      } catch (error) {
        console.error('保存项目失败:', error)
        ElMessage.error(isEdit.value ? '更新失败' : '添加失败')
      } finally {
        saveLoading.value = false
      }
    }
  })
}

// 删除项目
const handleDelete = (row) => {
  ElMessageBox.confirm('确定要删除该项目吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const response = await deleteProject(row.id)
      if (response.code === 200) {
        ElMessage.success('删除成功')
        loadData()
      } else {
        ElMessage.error(response.message || '删除失败')
      }
    } catch (error) {
      console.error('删除项目失败:', error)
      ElMessage.error('删除失败')
    }
  })
}

// 更新项目状态
const handleUpdateStatus = (row) => {
  let nextStatus = ''
  if (row.status === '未开始') {
    nextStatus = '报名中'
  } else if (row.status === '报名中') {
    nextStatus = '进行中'
  } else if (row.status === '进行中') {
    nextStatus = '已结束'
  } else if (row.status === '已结束') {
    nextStatus = '已取消'
  } else if (row.status === '已取消') {
    nextStatus = '未开始'
  }

  ElMessageBox.confirm(`确定要将项目状态从"${row.status}"更改为"${nextStatus}"吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const response = await updateProjectStatus(row.id, nextStatus)
      if (response.code === 200) {
        ElMessage.success('状态修改成功')
        loadData()
      } else {
        ElMessage.error(response.message || '状态修改失败')
      }
    } catch (error) {
      console.error('修改项目状态失败:', error)
      ElMessage.error('状态修改失败')
    }
  })
}

// 切换项目状态
const handleToggleStatus = async (row) => {
  // 添加加载状态
  row.statusLoading = true
  const newStatus = !row.isActive ? '已取消' : '未开始'

  try {
    const response = await updateProjectStatus(row.id, newStatus)
    if (response.code === 200) {
      row.status = newStatus
      ElMessage.success(`${newStatus === '已取消' ? '取消' : '激活'}成功`)
    } else {
      // 恢复原始状态
      row.isActive = !row.isActive
      ElMessage.error(response.message || `${newStatus === '已取消' ? '取消' : '激活'}失败`)
    }
  } catch (error) {
    // 恢复原始状态
    row.isActive = !row.isActive
    console.error(`${newStatus === '已取消' ? '取消' : '激活'}项目失败:`, error)
    ElMessage.error(`${newStatus === '已取消' ? '取消' : '激活'}失败`)
  } finally {
    row.statusLoading = false
  }
}

// 批量删除
const handleBatchDelete = () => {
  ElMessageBox.confirm(`确定要删除选中的 ${selectedProjects.value.length} 个项目吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    batchLoading.value = true
    try {
      const projectIds = selectedProjects.value.map(project => project.id)
      const response = await batchDeleteProjects(projectIds)
      if (response.code === 200) {
        ElMessage.success('批量删除成功')
        loadData()
        selectedProjects.value = []
      } else {
        ElMessage.error(response.message || '批量删除失败')
      }
    } catch (error) {
      console.error('批量删除失败:', error)
      ElMessage.error('批量删除失败')
    } finally {
      batchLoading.value = false
    }
  })
}

// 批量更新状态
const handleBatchUpdateStatus = (status) => {
  ElMessageBox.confirm(`确定要将选中的 ${selectedProjects.value.length} 个项目状态更改为"${status}"吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    batchLoading.value = true
    try {
      const projectIds = selectedProjects.value.map(project => project.id)
      const response = await batchUpdateProjectStatus(projectIds, status)
      if (response.code === 200) {
        ElMessage.success('批量更新状态成功')
        loadData()
        selectedProjects.value = []
      } else {
        ElMessage.error(response.message || '批量更新状态失败')
      }
    } catch (error) {
      console.error('批量更新状态失败:', error)
      ElMessage.error('批量更新状态失败')
    } finally {
      batchLoading.value = false
    }
  })
}

// 导出数据
const handleExport = async () => {
  exportLoading.value = true
  try {
    // 这里需要实现导出功能，可以调用后端接口或前端导出
    ElMessage.info('导出功能开发中...')
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error('导出失败')
  } finally {
    exportLoading.value = false
  }
}

// 关闭对话框
const handleDialogClose = () => {
  dialogVisible.value = false
  if (projectFormRef.value) {
    projectFormRef.value.resetFields()
  }
}

// 重置项目表单
const resetProjectForm = () => {
  Object.assign(projectForm, {
    id: null,
    name: '',
    type: '',
    genderLimit: '无',
    maxPlayers: 50,
    rounds: 1,
    ruleDescription: '',
    status: '未开始'
  })
  if (projectFormRef.value) {
    projectFormRef.value.resetFields()
  }
}

// 退出登录
const handleLogout = () => {
  ElMessageBox.confirm('确定要退出登录吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 清除用户信息
    store.commit('clearUser')
    localStorage.removeItem('user')
    localStorage.removeItem('token')
    // 跳转到登录页
    router.push('/login')
  })
}

// 导航到指定路径
const navigateTo = (path) => {
  router.push(path)
}

// 获取项目类型标签类型
const getTypeTagType = (type) => {
  const typeMap = {
    '径赛': 'primary',
    '田赛': 'success',
    '球类': 'warning',
    '其他': 'info'
  }
  return typeMap[type] || 'primary'
}

// 获取性别标签类型
const getGenderTagType = (genderLimit) => {
  const typeMap = {
    '男': 'primary',
    '女': 'danger',
    '无': 'info'
  }
  return typeMap[genderLimit] || 'info'
}

// 获取状态标签类型
const getStatusTagType = (status) => {
  const statusMap = {
    '未开始': 'info',
    '报名中': 'warning',
    '进行中': 'primary',
    '已结束': 'success',
    '已取消': 'danger'
  }
  return statusMap[status] || 'info'
}

// 获取状态按钮类型
const getStatusButtonType = (status) => {
  const buttonMap = {
    '未开始': 'primary',
    '报名中': 'warning',
    '进行中': 'success',
    '已结束': 'info',
    '已取消': 'danger'
  }
  return buttonMap[status] || 'primary'
}

// 获取报名百分比
const getRegistrationPercent = (project) => {
  if (!project.maxPlayers || project.maxPlayers === 0) return 0
  const percent = Math.round((project.registrationCount || 0) / project.maxPlayers * 100)
  return percent
}

// 格式化日期时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return '-'
  return new Date(dateTime).toLocaleString('zh-CN')
}

// 生命周期钩子
onMounted(() => {
  // 初始化数据
  initData()
})

</script>

<style scoped>
/* 基础样式 */
* {
  font-family: 'PingFang SC', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
  box-sizing: border-box;
}

/* 全局变量 */
:root {
  --primary-color: #2C5AA0;
  --primary-light: #E8EFF9;
  --primary-dark: #1E3D73;
  --success-color: #67C23A;
  --warning-color: #E6A23C;
  --danger-color: #F56C6C;
  --info-color: #909399;
  --text-primary: #303133;
  --text-regular: #606266;
  --text-secondary: #909399;
  --text-placeholder: #C0C4CC;
  --border-light: #EBEEF5;
  --border-base: #DCDFE6;
  --border-lighter: #F2F6FC;
  --background-base: #F5F7FA;
  --background-light: #FAFAFA;
}

/* 容器布局 */
.app-container {
  display: grid;
  grid-template-columns: 240px 1fr;
  grid-template-rows: 64px 1fr;
  min-height: 100vh;
  background-color: var(--background-base);
}

/* 顶部导航栏 */
.header {
  grid-column: 1 / -1;
  background-color: var(--primary-color);
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 24px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  position: relative;
  z-index: 100;
}

.logo {
  font-size: 20px;
  font-weight: 600;
  color: white;
  display: flex;
  align-items: center;
  gap: 12px;
  letter-spacing: 0.5px;
}

.flex-grow {
  flex-grow: 1;
}

/* 用户信息区域 */
.user-info {
  display: flex;
  align-items: center;
}

.user-avatar {
  display: flex;
  align-items: center;
  gap: 12px;
  cursor: pointer;
  padding: 8px 12px;
  border-radius: 6px;
  transition: background-color 0.3s;
}

.user-avatar:hover {
  background-color: rgba(255, 255, 255, 0.1);
}

.username {
  color: white;
  font-size: 14px;
  font-weight: 500;
}

/* 左侧导航栏 */
.sidebar {
  background-color: white;
  padding: 16px 0;
  border-right: 1px solid var(--border-light);
  box-shadow: 2px 0 8px rgba(0, 0, 0, 0.05);
  overflow-y: auto;
}

.menu-item {
  padding: 14px 24px;
  color: var(--text-regular);
  display: flex;
  align-items: center;
  gap: 12px;
  transition: all 0.3s ease;
  cursor: pointer;
  font-weight: 500;
  position: relative;
}

.menu-item:hover {
  background-color: var(--primary-light);
  color: var(--primary-color);
}

.menu-item.active {
  background-color: var(--primary-light);
  color: var(--primary-color);
}

.menu-item.active::before {
  content: '';
  position: absolute;
  left: 0;
  top: 0;
  bottom: 0;
  width: 4px;
  background-color: var(--primary-color);
}

.menu-item span {
  font-size: 15px;
}

/* 主内容区 */
.content {
  padding: 24px;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
  gap: 24px;
}

/* 页面标题区域 */
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  flex-wrap: wrap;
  gap: 16px;
}

.page-title h1 {
  font-size: 28px;
  font-weight: 600;
  color: var(--text-primary);
  margin: 0 0 8px 0;
}

.page-desc {
  font-size: 14px;
  color: var(--text-secondary);
  margin: 0;
}

.header-actions {
  display: flex;
  gap: 12px;
  align-items: center;
  flex-wrap: wrap;
}

/* 搜索卡片 */
.search-card {
  margin-bottom: 0;
}

.search-card :deep(.el-card__body) {
  padding: 24px;
}

.advanced-search {
  margin-top: 20px;
}

/* 表格卡片 */
.table-card {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.table-card :deep(.el-card__body) {
  padding: 0;
  flex: 1;
  display: flex;
  flex-direction: column;
}

/* 表格工具栏 */
.table-toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 24px;
  border-bottom: 1px solid var(--border-light);
}

.table-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.table-title {
  font-size: 16px;
  font-weight: 600;
  color: var(--text-primary);
}

.table-actions {
  display: flex;
  align-items: center;
  gap: 12px;
}

/* 表格样式 */
:deep(.el-table) {
  flex: 1;
  font-size: 14px;
}

:deep(.el-table th) {
  background-color: var(--background-light) !important;
  color: var(--text-primary);
  font-weight: 600;
}

:deep(.el-table td) {
  padding: 12px 0;
}

:deep(.el-table .el-table__row:hover > td) {
  background-color: var(--primary-light);
}

/* 报名信息样式 */
.registration-info {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.registration-percent {
  font-size: 12px;
  color: var(--text-secondary);
}

/* 表格操作按钮组 */
:deep(.el-button-group .el-button) {
  margin-left: 0;
}

:deep(.el-button-group .el-button + .el-button) {
  margin-left: 1px;
}

/* 分页容器 */
.pagination-container {
  padding: 16px 24px;
  display: flex;
  justify-content: flex-end;
  border-top: 1px solid var(--border-light);
}

/* 批量操作栏 */
.batch-operations {
  padding: 16px 24px;
  background-color: var(--primary-light);
  border-top: 1px solid var(--border-light);
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 12px;
}

.batch-info {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 500;
  color: var(--primary-color);
}

.batch-actions {
  display: flex;
  gap: 12px;
  flex-wrap: wrap;
}

/* 对话框样式 */
:deep(.el-dialog) {
  border-radius: 8px;
  overflow: hidden;
}

:deep(.el-dialog__header) {
  background-color: var(--primary-color);
  color: white;
  padding: 20px 24px;
}

:deep(.el-dialog__title) {
  color: white;
  font-weight: 600;
}

:deep(.el-dialog__headerbtn .el-dialog__close) {
  color: white;
}

:deep(.el-dialog__body) {
  padding: 24px;
}

:deep(.el-dialog__footer) {
  padding: 16px 24px;
  border-top: 1px solid var(--border-light);
}

/* 表单样式 */
:deep(.el-form-item__label) {
  font-weight: 500;
  color: var(--text-primary);
}

:deep(.el-input__inner) {
  border-radius: 4px;
}

:deep(.el-select .el-input .el-input__inner) {
  border-radius: 4px;
}

/* 项目详情样式 */
.project-detail {
  padding: 8px 0;
}

.rule-description {
  line-height: 1.6;
  color: var(--text-regular);
}

:deep(.el-descriptions__label) {
  font-weight: 600;
}

:deep(.el-descriptions__content) {
  color: var(--text-regular);
}

/* 按钮激活状态 */
:deep(.el-button.is-active) {
  background-color: var(--primary-color);
  border-color: var(--primary-color);
  color: white;
}

/* 消息提示样式 */
:deep(.el-message) {
  border-radius: 4px;
}

:deep(.el-message-box) {
  border-radius: 8px;
}


/* 动画效果 */
.el-fade-in-enter-active,
.el-fade-in-leave-active {
  transition: opacity 0.3s ease;
}

.el-fade-in-enter-from,
.el-fade-in-leave-to {
  opacity: 0;
}

.el-zoom-in-enter-active,
.el-zoom-in-leave-active {
  transition: all 0.3s ease;
}

.el-zoom-in-enter-from,
.el-zoom-in-leave-to {
  transform: scale(0.9);
  opacity: 0;
}

/* 自定义滚动条 */
::-webkit-scrollbar {
  width: 8px;
  height: 8px;
}

::-webkit-scrollbar-track {
  background: var(--background-light);
  border-radius: 4px;
}

::-webkit-scrollbar-thumb {
  background: var(--border-base);
  border-radius: 4px;
}

::-webkit-scrollbar-thumb:hover {
  background: var(--text-placeholder);
}
</style>